package com.alipay.rebate.shop.controller.customer;

import com.alipay.rebate.shop.checker.ParameterChecker;
import com.alipay.rebate.shop.constants.PatternContant;
import com.alipay.rebate.shop.constants.RedisConstant;
import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.core.ResultGenerator;
import com.alipay.rebate.shop.dao.mapper.InviteShareUrlSettingsMapper;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.exceptoin.MobileCodeNotRightException;
import com.alipay.rebate.shop.helper.ExtraHelper;
import com.alipay.rebate.shop.helper.InterfaceStatisticsHelper;
import com.alipay.rebate.shop.model.InviteShareUrlSettings;
import com.alipay.rebate.shop.model.User;
import com.alipay.rebate.shop.pojo.common.ResponseResult;
import com.alipay.rebate.shop.pojo.dataoke.DataokePrivilegeLinkRsp;
import com.alipay.rebate.shop.pojo.dataoke.DataokeProductListRsp;
import com.alipay.rebate.shop.pojo.dataoke.FriendsCircleListReq;
import com.alipay.rebate.shop.pojo.pdtframework.ProductRepoChoiceRsp;
import com.alipay.rebate.shop.pojo.taobao.TpwdRequest;
import com.alipay.rebate.shop.pojo.user.AccountLoginRequest;
import com.alipay.rebate.shop.pojo.user.ShareUrlResponse;
import com.alipay.rebate.shop.pojo.user.TaobaoAuthReq;
import com.alipay.rebate.shop.pojo.user.TaobaoAuthRsp;
import com.alipay.rebate.shop.pojo.user.TokenRsp;
import com.alipay.rebate.shop.pojo.user.customer.*;
import com.alipay.rebate.shop.pojo.user.product.CheckActivityConditionReq;
import com.alipay.rebate.shop.pojo.user.product.CheckActivityConditionRsp;
import com.alipay.rebate.shop.service.customer.CustomerUserService;
import com.alipay.rebate.shop.utils.DataokeUtil;
import com.alipay.rebate.shop.utils.JwtUtils;
import com.alipay.rebate.shop.utils.TaobaoUtil;
import com.alipay.rebate.shop.utils.TokenUtil;
import com.taobao.api.ApiException;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.Validator;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.hibernate.validator.constraints.Length;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CustomerUserController {

    private final static Logger logger = LoggerFactory.getLogger(CustomerUserController.class);

    @Value("${rebateshop.domain}")
    String domain;
    @Value("${rebateshop.protocol}")
    String protocol;
    @Value("${rebateshop.share.interface}")
    String shareInterface;
    @Autowired
    CustomerUserService userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    Validator validator;
    @Autowired
    ParameterChecker parameterChecker;
    @Autowired
    InviteShareUrlSettingsMapper inviteShareUrlSettingsMapper;
    @Autowired
    ExtraHelper extraHelper;
    @Autowired
    UserMapper usermapper;

    @GetMapping("/customer/generateShareUrl")
    @ResponseBody
    public  ResponseResult<ShareUrlResponse> generateShareUrl(HttpServletRequest request){
        logger.debug("request is : {}",request);
        // 从登陆时返回的token中那种用户id和手机号码，拼接url
        long id = JwtUtils.getUserIdFromToken(request);
        String token = TokenUtil.genToken(id);
        InviteShareUrlSettings inviteShareUrlSettings = inviteShareUrlSettingsMapper.selectByPrimaryKey(1);
        String url = inviteShareUrlSettings.getUrl() +"?parentUserId=" +id + "&token=" + token;
        // 生成新的用于h5注册时用的token
        ShareUrlResponse shareUrlResponse = new ShareUrlResponse();
        shareUrlResponse.setUrl(url);
        shareUrlResponse.setToken(token);
        return ResultGenerator.genSuccessResponseResult(shareUrlResponse);
    }

    @PostMapping("/customer/register")
    @ResponseBody
    public ResponseResult<Void> register(
            @RequestBody UserRequest userRequest,
            HttpServletRequest request
        ){
        logger.debug("request UserRequest from request: {}", userRequest);
        ResponseResult<Void> responseResult = new ResponseResult<>();
        // 查看验证码是否正确
        String key = RedisConstant.getRegisterRedisKey(userRequest.getUserPhone());
//        String mobileCode = userRequest.getMobileCode();
        String mobileCode = stringRedisTemplate.opsForValue().get(key);
        logger.debug("mobileCode from redis is : {}", mobileCode);
        logger.debug("mobileCode from request is : {}", userRequest.getMobileCode());
        // h5手机号注册
        if (userRequest.getParentUserId() != null) {
            logger.debug("h5 register");
            parameterChecker.checkH5Register(userRequest);
            checkMobileCode(userRequest.getMobileCode(),mobileCode);
            userService.h5Register(userRequest,request);
            stringRedisTemplate.delete(key);
            return responseResult;
        }
        // 微信注册
        if (!StringUtils.isEmpty(userRequest.getOpenId())) {
            logger.debug("weixin register");
            parameterChecker.checkWeixinRegister(userRequest);
            checkMobileCode(userRequest.getMobileCode(),mobileCode);
            userService.weixinRegister(userRequest,request);
            stringRedisTemplate.delete(key);
            return responseResult;
        }
        // 手机号注册
        if (StringUtils.isEmpty(userRequest.getOpenId()) &&
                !StringUtils.isEmpty(userRequest.getUserPhone())) {
            logger.debug("phone register");
            parameterChecker.checkPhoneRegister(userRequest);
            checkMobileCode(userRequest.getMobileCode(),mobileCode);
            userService.phoneRegister(userRequest,request);
            stringRedisTemplate.delete(key);
            return responseResult;
        }
        return responseResult;
    }


    @PostMapping("/common/userRegister")
    @ResponseBody
    public ResponseResult<Void> userRegister(
            @RequestBody UserRequest userRequest,
            HttpServletRequest request
    ){
        logger.debug("request UserRequest from request: {}", userRequest);
        ResponseResult<Void> responseResult = new ResponseResult<>();
        // 查看验证码是否正确
        String key = RedisConstant.getRegisterRedisKey(userRequest.getUserPhone());
        String mobileCode = stringRedisTemplate.opsForValue().get(key);
        logger.debug("mobileCode from redis is : {}", mobileCode);
        logger.debug("mobileCode from request is : {}", userRequest.getMobileCode());
        // h5手机号注册
        if (userRequest.getParentUserId() != null) {
            checkMobileCode(userRequest.getMobileCode(),mobileCode);
            userService.h5Register(userRequest,request);
            stringRedisTemplate.delete(key);
            return responseResult;
        }
        // 微信注册
        if (!StringUtils.isEmpty(userRequest.getOpenId())) {
            checkMobileCode(userRequest.getMobileCode(),mobileCode);
            userService.weixinRegister(userRequest,request);
            stringRedisTemplate.delete(key);
            return responseResult;
        }
        // 手机号注册
        if (StringUtils.isEmpty(userRequest.getOpenId()) &&
                !StringUtils.isEmpty(userRequest.getUserPhone())) {
            checkMobileCode(userRequest.getMobileCode(),mobileCode);
            userService.phoneRegister(userRequest,request);
            stringRedisTemplate.delete(key);
            return responseResult;
        }
        return responseResult;
    }


    private void checkMobileCode(String userMobileCode, String redisMobileCode){
        if(!userMobileCode.equals(redisMobileCode)){
            logger.debug("mobileCode not right");
            throw new MobileCodeNotRightException();
        }
    }

    @PostMapping(value = "/common/login")
    @ResponseBody
    public ResponseResult login(
            @RequestBody UserDto loginInfo,
            HttpServletRequest request,
            HttpServletResponse response
    ){
        // 获取主题信息
        Subject subject = SecurityUtils.getSubject();
        logger.debug("Login subject is : {}",subject);
        logger.debug("Login UserDto is : {}",loginInfo);

        // 微信登陆
        if(!StringUtils.isEmpty(loginInfo.getOpenId())){
            logger.debug("weixin login");
            WeixinLoginRequest weixinLoginRequest = new WeixinLoginRequest();
            weixinLoginRequest.setOpenId(loginInfo.getOpenId());
            weixinLoginRequest.setLoginPlatform(loginInfo.getLoginPlatform());
            logger.debug("WeixinLoginRequest is : {}",weixinLoginRequest);
            parameterChecker.checkParams(weixinLoginRequest);
            UserPersonalCenterResponse data = userService.weixinLogin(loginInfo,request,response,subject);
            return ResultGenerator.genSuccessResponseResult(data);
        }
        // 账号密码登陆
        if(loginInfo.getPassword() != null){
            logger.debug("password login");
            AccountLoginRequest accountLoginRequest = new AccountLoginRequest();
            accountLoginRequest.setAccount(loginInfo.getAccount());
            accountLoginRequest.setPassword(
                    loginInfo.getPassword() == null ?
                            null: String.valueOf(loginInfo.getPassword())
            );
            accountLoginRequest.setLoginPlatform(loginInfo.getLoginPlatform());
            logger.debug("AccountLoginRequest is : {}",accountLoginRequest);
            parameterChecker.checkParams(accountLoginRequest);
            UserPersonalCenterResponse data = userService.userNamePasswordLogin(loginInfo,request,response,subject);
            return ResultGenerator.genSuccessResponseResult(data);
        }
        return null;
    }

    @RequestMapping(value = "/logout")
    public ResponseResult logout(
        HttpServletRequest request
    ) {
        ResponseResult responseResult = new ResponseResult();
        SecurityUtils.getSubject().logout();
        return responseResult;
    }


//    @RequestMapping(value = "/logoff")
//    public ResponseResult logoff(
//        HttpServletRequest request
//    ) {
//        ResponseResult responseResult = new ResponseResult();
//        long userId = JwtUtils.getUserIdFromToken(request);
//        SecurityUtils.getSubject().logout();
//        userService.logoff(userId);
//        return responseResult;
//    }



    @PutMapping("/customer/updateHeadImageUrl")
    @ResponseBody
    public ResponseResult<Void> updateHeadImageUrl(
        HttpServletRequest request,
        @RequestBody @Valid UpdateHeadImageUrlRequest updateHeadImageUrlRequest){
        logger.debug("Get into updateHeadImageUrl method");
        logger.debug("UpdateHeadImageUrlRequest is: {}",updateHeadImageUrlRequest);
        long userId = JwtUtils.getUserIdFromToken(request);
        User user = new User();
        user.setUserId(userId);
        user.setUserHeadImage(updateHeadImageUrlRequest.getHeadImageUrl());
        userService.update(user);
        return ResultGenerator.genSuccessResponseResult(null);
    }

    @PutMapping("/customer/updateUserNickName")
    @ResponseBody
    public ResponseResult<Void> updateUserNickName(
            @RequestBody @Valid UpdateUserNickNameRequest updateUserNickNameRequest,
            HttpServletRequest request){
        logger.debug("Get into updateUserNickName method");
        long userId = JwtUtils.getUserIdFromToken(request);
        User user = new User();
        user.setUserId(userId);
        user.setUserNickName(updateUserNickNameRequest.getUserNickName());
        userService.update(user);
        return ResultGenerator.genSuccessResponseResult(null);
    }

    @GetMapping("/customer/generateValidCodeByType")
    @ResponseBody
    public ResponseResult<String> generateValidCodeByType(
            @NotNull(message = PatternContant.PHONE_NULL_MESSAGE)
            @Pattern(regexp= PatternContant.PHONE_PATTERN,
                    message=PatternContant.PHONE_PATTERN_ERROR_MESSAGE)
            String phone,
            @NotNull(message = "type 不能为空")
            Integer type,
            HttpServletRequest request
    ){
        logger.debug("phone received from request is : {}",phone);
        logger.debug("type received from request is : {}",type);
        String data = userService.generateValidCodeByType(phone,type,request);
        return ResultGenerator.genSuccessResponseResult(data);
    }

    @GetMapping("/customer/generateInternationalValidCodeByType")
    @ResponseBody
    public ResponseResult<String> generateInternationalValidCodeByType(
            @NotNull(message = PatternContant.PHONE_NULL_MESSAGE)
                    String phone,
            @NotNull(message = "type 不能为空")
                    Integer type,
                    String areaCode,
            HttpServletRequest request
    ){
        logger.debug("phone received from request is : {}",phone);
        logger.debug("type received from request is : {}",type);
        String data = userService.generateInternationalValidCodeByType(areaCode,phone,type,request);
        return ResultGenerator.genSuccessResponseResult(data);
    }


    @PutMapping("/customer/updateAlipayAccount")
    @ResponseBody
    public ResponseResult<Void> updateAlipayAccount(
            @RequestBody @Valid UpdateAlipayAccountRequest updateAlipayAccountRequest,
            HttpServletRequest request){
        logger.debug("received UpdateAlipayAccountRequest is: {}",updateAlipayAccountRequest);
        long userId = JwtUtils.getUserIdFromToken(request);
        UserRequest userRequest = new UserRequest();
        userRequest.setAlipayAccount(updateAlipayAccountRequest.getAlipayAccount());
        userRequest.setMobileCode(updateAlipayAccountRequest.getMobileCode());
        userRequest.setRealName(updateAlipayAccountRequest.getRealName());
        userService.updateAlipayAccount(userRequest,userId);
        return ResultGenerator.genSuccessResponseResult(null);
    }

    @PostMapping("/customer/checkOriginalValidCode")
    @ResponseBody
    public ResponseResult<Void> checkOriginalValidCode(@RequestBody @Valid CheckOriginalPhoneRequest checkOriginalPhoneRequest){
        logger.debug("received CheckOriginalPhoneRequest is : {}",checkOriginalPhoneRequest);
        ResponseResult<Void> responseResult = new ResponseResult<>();
        String key = RedisConstant.MOBILE_CODE_CUSTOMER_ORIGINAL_PHONE_PREFIX + checkOriginalPhoneRequest.getUserPhone();
        String mobileCode = stringRedisTemplate.opsForValue().get(key);
        if(!checkOriginalPhoneRequest.getMobileCode().equals(mobileCode)){
            responseResult.setStatus(StatusCode.MOBILE_CODE_NOT_RIGHT.getCode());
        }
        return responseResult;
    }

    @PutMapping("/customer/updatePhone")
    @ResponseBody
    public ResponseResult<Void> updatePhone(
        @RequestBody @Valid UpdatePhoneRequest updatePhoneRequest,
        HttpServletRequest request){
        logger.debug("received UserRequest is: {}",updatePhoneRequest);
        UserRequest userRequest = new UserRequest();
        userRequest.setUserPhone(updatePhoneRequest.getUserPhone());
        userRequest.setMobileCode(updatePhoneRequest.getMobileCode());
        userRequest.setAreaCode(updatePhoneRequest.getAreaCode());
        long userId = JwtUtils.getUserIdFromToken(request);
        userService.updatePhone(userRequest,userId);
        return ResultGenerator.genSuccessResponseResult(null);
    }

    @PutMapping("/customer/updatePassword")
    @ResponseBody
    public ResponseResult<Void> updatePassword(
        @RequestBody @Valid UpdatePasswordRequest updatePasswordRequest,
        HttpServletRequest request){
        logger.debug("received UpdatePasswordRequest is: {}",updatePasswordRequest);
        UserRequest userRequest = new UserRequest();
        userRequest.setUserPhone(updatePasswordRequest.getUserPhone());
        userRequest.setMobileCode(updatePasswordRequest.getMobileCode());
        userRequest.setPassword(updatePasswordRequest.getPassword());
        long userId = JwtUtils.getUserIdFromToken(request);
        userService.updatePassword(userRequest,userId);
        return ResultGenerator.genSuccessResponseResult(null);
    }

    @GetMapping("/customer/getAliPayMessage")
    @ResponseBody
    public ResponseResult<UserAlipayResponse> getAliPayMessage(HttpServletRequest request){
        long userId = JwtUtils.getUserIdFromToken(request);
        return userService.getAliPayMessage(userId);
    }

    @GetMapping("/customer/getPersonalCenterMessage")
    @ResponseBody
    public ResponseResult<UserPersonalCenterResponse> getPersonalCenterMessage(HttpServletRequest request){
        long userId = JwtUtils.getUserIdFromToken(request);
        UserPersonalCenterResponse data = userService.getPersonalCenterMessage(userId);
        return ResultGenerator.genSuccessResponseResult(data);
    }

    @GetMapping("/customer/getPrivilegeLink")
    @ResponseBody
    public ResponseResult<Object> getPrivilegeLink(
            @NotNull(message = PatternContant.GOODSID_ERROR_MESSAGE)
            String goodsId
    ){
        DataokePrivilegeLinkRsp dataokeResponse = DataokeUtil.getPrivilegeLink(goodsId);
        return ResultGenerator.genSuccessResponseResult(dataokeResponse.getData());
    }

    @RequestMapping("/customer/generateRelationIdAndSpecialId")
    @ResponseBody
    public ResponseResult<UserRelationIdResponse> generateRelationIdAndSpecialId(
            @NotNull(message = PatternContant.SESSIONKEY_ERROR_MESSAGE)
            String token,
            HttpServletRequest request){
        logger.debug("get sessionKey from request is : {}",token);
        long userId = JwtUtils.getUserIdFromToken(request);
        UserRelationIdResponse data = userService.generateRelationAndSpecialId(token,userId);
        return ResultGenerator.genSuccessResponseResult(data);
    }

    @GetMapping("/customer/getTpwd")
    @ResponseBody
    public ResponseResult<String> getTpwd(
            String userId,
            @NotNull(message = PatternContant.TPWD_TEXT_ERROR_MESSAGE)
            @Length(min = 5,message = PatternContant.TPWD_TEXT_RANGE_ERROR_MESSAGE)
            String text,
            @NotNull(message = PatternContant.TPWD_URL_ERROR_MESSAGE)
            String url,
            String logo,
            String ext
    ){
        logger.debug("userId is : {}",userId);
        logger.debug("text is : {}",text);
        logger.debug("url is : {}",url);
        logger.debug("logo is : {}",logo);

        TpwdRequest tpwdRequest = new TpwdRequest();
        tpwdRequest.setUser_id(userId);
        tpwdRequest.setText(text);
        tpwdRequest.setUrl(url);
        tpwdRequest.setLogo(logo);
        tpwdRequest.setExt(ext);
        String data = TaobaoUtil.getTpwd(tpwdRequest);
        return ResultGenerator.genSuccessResponseResult(data);
    }


    @PostMapping("/customer/getPwd")
    @ResponseBody
    public ResponseResult<String> getPwd(@RequestBody TpwdRequest request){
        logger.debug("request is : {}",request);
        String data = TaobaoUtil.getTpwd(request);
        return ResultGenerator.genSuccessResponseResult(data);
    }




    @GetMapping("/customer/getPrivilegeLinkAndTpwd")
    @ResponseBody
    public ResponseResult<PrivilegeLinkAndTpwdResponse> getPrivilegeLinkAndTpwd(
        @NotNull(message = PatternContant.GOODSID_ERROR_MESSAGE)
        String goodsId,
        String userId,
        String userName,
        @NotNull(message = PatternContant.TPWD_TEXT_ERROR_MESSAGE)
        @Length(min = 5,message = PatternContant.TPWD_TEXT_RANGE_ERROR_MESSAGE)
        String text,
        @NotNull(message = PatternContant.TPWD_LOGO_ERROR_MESSAGE)
        String logo,
        String accessToken,
        boolean flag,
        Long relationId,
        Long specialId,
        String extra,
        HttpServletRequest request
    ) throws ApiException {

        logger.debug("flag,taobaoUserId,relationId is : {},{},{}",flag,userId,relationId);
        parameterChecker.checkGetPrivilegeLinkAndTpwd(userId,userName,accessToken,flag,relationId,specialId);
        Long id = JwtUtils.getUserIdFromToken(request);
        PrivilegeLinkAndTpwdResponse rsp = userService.getPrivilegeLinkAndTpwd(flag,goodsId, userId, userName, text,
        logo, accessToken, relationId, specialId, id, extra);
        extraHelper.checkExtra(extra);
        return ResultGenerator.genSuccessResponseResult(rsp);
    }

    @PostMapping("/customer/getMultiPrivilegeLinkAndTpwd")
    @ResponseBody
    public ResponseResult<List<PrivilegeLinkAndTpwdResponse>> getMultiPrivilegeLinkAndTpwd(
        @RequestBody MultiPrivilegeLinkRequest privilegeLinkRequest,
        HttpServletRequest request
    ) throws ApiException {

        logger.debug("MultiPrivilegeLinkRequest : {}",privilegeLinkRequest);

        parameterChecker.checkParams(privilegeLinkRequest);
        parameterChecker.checkGetPrivilegeLinkAndTpwd(
            privilegeLinkRequest.getUserId(),
            privilegeLinkRequest.getUserName(),
            privilegeLinkRequest.getAccessToken(),
            privilegeLinkRequest.isFlag(),
            privilegeLinkRequest.getRelationId(),
            privilegeLinkRequest.getSpecialId());

        Long id = JwtUtils.getUserIdFromToken(request);
        List<PrivilegeLinkAndTpwdResponse> data =
            userService.getMultiPrivilegeLinkAndTpwd(privilegeLinkRequest, id);
        return ResultGenerator.genSuccessResponseResult(data);
    }

    /**
     * 找回密码
     * @return
     */
    @PostMapping("/customer/findPassword")
    @ResponseBody
    public ResponseResult<Void>  findPassword(
            @RequestBody @Valid PasswordRequest passwordRequest
    ){
        userService.findPassword(passwordRequest);
        return ResultGenerator.genSuccessResponseResult(null);
    }

    @GetMapping("/customer/getOneLevelFansDetail")
    @ResponseBody
    public ResponseResult getOneLevelFansDetail(
        HttpServletRequest request,
        Integer pageNo,
        Integer pageSize,
        String userNameOrPhone
    ){
        long userId = JwtUtils.getUserIdFromToken(request);
        pageNo = parameterChecker.checkAndGetPageNo(pageNo);
        pageSize = parameterChecker.checkAndGetPageSize(pageSize);
        UserFansListResponse rsp = userService.getOneLevelFansDetail(pageNo,pageSize, userId,userNameOrPhone);
        return ResultGenerator.genSuccessResponseResult(rsp);
    }

    @GetMapping("/customer/getSecondLevelFansDetail")
    @ResponseBody
    public ResponseResult getSecondLevelFansDetail(
        HttpServletRequest request,
        Integer pageNo,
        Integer pageSize,
        String userNameOrPhone
    ){
        long userId = JwtUtils.getUserIdFromToken(request);
        pageNo = parameterChecker.checkAndGetPageNo(pageNo);
        pageSize = parameterChecker.checkAndGetPageSize(pageSize);
        UserFansListResponse rsp = userService.getSecondLevelFansDetail(pageNo,pageSize, userId,userNameOrPhone);
        return ResultGenerator.genSuccessResponseResult(rsp);
    }

    @GetMapping("/customer/getUserIncomeRecordDetail")
    @ResponseBody
    public ResponseResult<UserIncomeRecordResponse> getUserIncomeRecordDetail(
            HttpServletRequest request
    ){
        long userId = JwtUtils.getUserIdFromToken(request);
        return userService.getUserIncomeRecordDetail(userId);
    }

    @PostMapping("/customer/checkIfUserCanBuyFreeActivityProduct")
    @ResponseBody
    public ResponseResult<CheckActivityConditionRsp> checkIfUserCanBuyFreeActivityProduct(
        @RequestBody  CheckActivityConditionReq req,
        HttpServletRequest request
    ){
        long id = JwtUtils.getUserIdFromToken(request);
        logger.debug("CheckActivityConditionReq is : {}",req);
        parameterChecker.checkParams(req);
        parameterChecker.checkTaoBaoInfoWhenFlagFalse(req.getUserId(),req.getUserName(),req.getAccess_token(),req.isFlag());
        parameterChecker.checkActivityJson(req);
        CheckActivityConditionRsp data = userService.checkIfUserCanBuyActivity(
            id, req.getGoodsId(), req.isFlag(), req.getAccess_token(),
            req.getUserId(), req.getUserName(), req.getActivityId(),
            req.getProductRepoId(), req.getJson(),req.getItemType());
        return ResultGenerator.genSuccessResponseResult(data);

    }

    @PostMapping("/customer/rewardUit")
    @ResponseBody
    public ResponseResult<Integer> rewardUit(
        HttpServletRequest request
    ){
        Long userId = JwtUtils.getUserIdFromToken(request);
        userService.rewardUser(userId);
        return ResultGenerator.genSuccessResponseResult(null);
}

    @GetMapping("/customer/decodeSecretAndBindRelation")
    @ResponseBody
    public ResponseResult<ProductRepoChoiceRsp> decodeSecretAndBindRelation(
        @RequestParam String sk,
        HttpServletRequest request
    ){
        Long userId = JwtUtils.getUserIdFromToken(request);
        ProductRepoChoiceRsp productRepoChoiceRsp =
            userService.decodeSecretAndBindRelation(sk,userId);
        return ResultGenerator.genSuccessResponseResult(productRepoChoiceRsp);
    }

    @PostMapping("/customer/taobaoAuth")
    @ResponseBody
    public ResponseResult<TaobaoAuthRsp> taobaoAuth(
        @RequestBody TaobaoAuthReq taobaoAuthReq,
        HttpServletRequest request
    ){
        logger.debug("TaobaoAuthReq:{},{},{}{}", taobaoAuthReq);
        Long platformUserId = JwtUtils.getUserIdFromToken(request);
        TaobaoAuthRsp  taobaoAuthRsp =
            userService.taobaoAuth(platformUserId,taobaoAuthReq.getUserId(),
            taobaoAuthReq.getUserName(),taobaoAuthReq.getAccessToken());
        return ResultGenerator.genSuccessResponseResult(taobaoAuthRsp);
    }

    @PostMapping("/customer/plusOrReduceVirtualMoney")
    @ResponseBody
    public ResponseResult<Void> plusOrReduceVirtualMoney(
        @RequestBody PlusOrReduceVirMoneyReq req,
        HttpServletRequest request
    ){
        parameterChecker.checkParams(req);
        parameterChecker.checkPlusOrReduceVirMoneyReq(req);
        Long userId = JwtUtils.getUserIdFromToken(request);
        userService.plusOrReduceVirtualMoney(req,userId);
        return ResultGenerator.genSuccessResponseResult(null);
    }

    @GetMapping("/customer/selectInviteDetail")
    @ResponseBody
    public ResponseResult<Map<String, InviteDetailRsp>> selectInviteDetail(
        HttpServletRequest request
    ){
        Long userId = JwtUtils.getUserIdFromToken(request);
        Map<String, InviteDetailRsp> data = userService.selectInviteDetail(userId);
        return ResultGenerator.genSuccessResponseResult(data);
    }

    @RequestMapping("/customer/checkRelationId")
    @ResponseBody
    public ResponseResult<Boolean> checkRelationId(
        @RequestParam("relationId") Long relationId,
        HttpServletRequest request
    ){
        Long userId = JwtUtils.getUserIdFromToken(request);
        boolean data = userService.checkRelationId(userId,relationId);
        return ResultGenerator.genSuccessResponseResult(data);
    }


    @PostMapping("/customer/weixinAuth")
    @ResponseBody
    public ResponseResult weixinAuth(
        @RequestBody UserRequest userRequest,
        HttpServletRequest request
    ){

        long userId = JwtUtils.getUserIdFromToken(request);
        logger.debug("userId is : {}",userId);
        String openId = userRequest.getOpenId();
        userService.weixinAuth(userId,openId);
        return ResultGenerator.genSuccessResponseResult();

    }

    @PutMapping("/customer/updateUserInfoNeed")
    @ResponseBody
    public ResponseResult<Void> updateUserNickName(
        @RequestBody UpdateUserInfoReq updateUserInfoReq,
        HttpServletRequest request){
        logger.debug("Get into updateUserNickName method");
        long userId = JwtUtils.getUserIdFromToken(request);
        User user = new User();
        user.setUserId(userId);
        if (updateUserInfoReq.getPrivacyProtection() == null) {
            user.setLoginPlatform(updateUserInfoReq.getLoginPlatform());
            user.setDeviceModel(updateUserInfoReq.getDeviceModel());
            user.setLatelyActiveTime(new Date());
        }
        if (updateUserInfoReq.getPrivacyProtection() != null) {
            if (updateUserInfoReq.getPrivacyProtection() == 1 || updateUserInfoReq.getPrivacyProtection() == 0) {
                logger.debug("getPrivacyProtection is : {}", updateUserInfoReq.getPrivacyProtection());
                user.setPrivacyProtection(updateUserInfoReq.getPrivacyProtection());
            }
        }
//        userService.update(user);
        usermapper.updateUser(user);
        return ResultGenerator.genSuccessResponseResult(null);
    }

    @GetMapping("/customer/getNewToken")
    @ResponseBody
    public ResponseResult<TokenRsp> getNewToken(
        HttpServletRequest request
    ){
        long userId = JwtUtils.getUserIdFromToken(request);
        TokenRsp tokenRsp = userService.getNewToken(userId);
        return ResultGenerator.genSuccessResponseResult(tokenRsp);
    }


    @GetMapping("/customer/openOauth")
    @ResponseBody
    public ResponseResult<Map<String,String>> openOauth(){
        return ResultGenerator.genSuccessResponseResult(TaobaoUtil.openOauth());
    }

    @PostMapping("/customer/getTaoBaoInformation")
    @ResponseBody
    public ResponseResult<Object> getTaoBaoInformation(@NotNull(message = "code参数不能为空") String code) throws IOException {
        return ResultGenerator.genSuccessResponseResult(TaobaoUtil.getTaoBaoInformation(code));
    }
    @GetMapping("/common/getFriendsCircleListReq")
    @ResponseBody
    public Object getFriendsCircleListReq(FriendsCircleListReq req) throws Exception {
        return DataokeUtil.getFriendsCircleListReq(req);
    }

    @GetMapping("/common/getFriendsCircleList")
    @ResponseBody
    public DataokeProductListRsp getFriendsCircleListReqTwo(String pageId) throws Exception {
        return DataokeUtil.getFriendsCircleListReqTwo(pageId);
    }
}
